package com.fjzx.androidframe.network;

import android.arch.lifecycle.LiveData;
import android.arch.paging.DataSource;
import android.arch.paging.LivePagedListBuilder;
import android.arch.paging.PageKeyedDataSource;
import android.arch.paging.PagedList;
import android.support.annotation.NonNull;

import com.fjzx.androidframe.network.callback.PagedCallback;
import com.fjzx.androidframe.xlogger.XLogger;


/**
 * 分页网络请求数据源工厂类
 * 用于分页请求服务器数据
 *
 * @param <T>
 * @author xiongyongcong
 */
public abstract class PagedNetworkDataSourceFactory<T> extends DataSource.Factory<Integer, T> {
    @Override
    public DataSource create() {
        return new PagedNetDataSource();
    }

    public class PagedNetDataSource<T> extends PageKeyedDataSource<Integer, T> {
        @Override
        public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, T> callback) {
            // 首次请求，请求第一页的数据
            XLogger.d("PagedNetDataSource loadInitial");
            load(1, (PagedCallback) data -> callback.onResult(data, 0, 2));
        }

        @Override
        public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, T> callback) {
            // 当PagedList触发底部加载更多的时候，回调此处，加载更多数据
            XLogger.d("PagedNetDataSource loadAfter, page: " + params.key);
            load(params.key, (PagedCallback) data -> callback.onResult(data, params.key + 1));
        }

        @Override
        public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, T> callback) {
        }
    }

    /**
     * 生成分页的LiveData
     *
     * @return
     */
    public LiveData<PagedList<T>> build() {
        return new LivePagedListBuilder<>(this, pageConfig())
                .build();
    }

    /**
     * 每页数据大小
     *
     * @return
     */
    protected int pageSize() {
        return 10;
    }

    /**
     * 分页配置
     *
     * @return
     */
    protected PagedList.Config pageConfig() {
        return new PagedList.Config.Builder()
                .setPageSize(pageSize())
                .setEnablePlaceholders(true)
                .setPrefetchDistance(pageSize() / 2)
                .build();
    }

    /**
     * 子类重写此方法，从网络获取数据
     *
     * @param page
     * @param callback
     */
    public abstract void load(int page, PagedCallback<T> callback);
}
